package com.xm9m.web.service.api;

import com.salesmanager.core.modules.sms.SmsService;
import com.salesmanager.core.business.customer.model.Customer;
import com.salesmanager.core.business.customer.service.CustomerService;
import com.salesmanager.core.modules.sms.SmsTemplate;
import com.salesmanager.core.utils.CoreConfiguration;
import com.salesmanager.core.utils.MD5Util;
import com.salesmanager.web.constants.Constants;
import com.salesmanager.web.entity.SMSMessage;
import com.salesmanager.web.entity.SMSType;
import com.salesmanager.web.utils.SMS.GenerationSmsCode;
import com.salesmanager.web.utils.SMS.JavaSmsApi;
import com.salesmanager.web.utils.SMS.ValidateCode;
import com.xm9m.web.service.api.request.CaptchaRequest;
import com.xm9m.web.service.api.response.CaptchaResponse;
import com.xm9m.web.service.constants.ResultMessage;
import com.xm9m.web.service.constants.StatusCode;
import com.xm9m.web.service.interfaces.AbstractRestApi;
import com.xm9m.web.service.interfaces.IXm9mResponse;
import com.xm9m.web.service.internal.util.BuildResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;


public class CaptchaGet extends AbstractRestApi {

    private static final Logger logger = LoggerFactory.getLogger(CaptchaGet.class);

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CoreConfiguration coreConfiguration;

    @Autowired
    private SmsService smsService;

    @Autowired
    private SmsService SmsServiceDayu;

    @SuppressWarnings("unchecked")
    @Override
    public <T extends IXm9mResponse> T execute(String requestData, String version) {
        CaptchaResponse captchaResponse = new CaptchaResponse();
        CaptchaRequest captchaRequest = super.json2Bean(requestData, CaptchaRequest.class);
        if (captchaRequest == null) {
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
        }

        //未知设备
        if (captchaRequest.getAppType() == null) {
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
        }

        if (captchaRequest.getAppType() == 2) {
            //
        }

        Customer customer = customerService.getByTelphone(captchaRequest.getMobile());
        //根据短信类型验证
        if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_REGISTER.getValue())) {
            if (customer != null) {
                return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.USER_EXISTS);
            }
        } else if (captchaRequest.getType().toString().equals(SMSType.TELEPHONE_BIND.getValue())) {
            if (customer != null) {
                return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.DEVICE_ALREADY_BIND);
            }
        } else if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_PASSWORD_FORGET.getValue())) {
            if (customer == null) {
                return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.USER_NO_EXISTS);
            }
        } else if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_PASSWORD_CHANGE.getValue())) {
            if (customer == null) {
                return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.USER_NO_EXISTS);
            }
        } else if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_BIND_ALIPAY.getValue())) {
            if (customer == null) {
                return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.USER_NO_EXISTS);
            }
        } else {
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
        }
        //发送短信
        String debug = coreConfiguration.getProperty(Constants.SMS_DEBUG);
        SMSMessage smsMessage = (SMSMessage) smsService.getByTelephone(captchaRequest.getMobile());
        if (smsMessage == null) {
            smsMessage = createMessage(captchaRequest, debug);
        } else {
            if (!ValidateCode.diff(smsMessage)) {
                return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.SMS_SENDING);
            }
            //如果类型不同需要重新创建一个
            if (!smsMessage.getType().equals(captchaRequest.getType().toString())) {
                smsMessage = createMessage(captchaRequest, debug);
            }
        }
        try {
            String ss;
            if (!debug.equals("true")) {
                //注册信息用阿里大鱼发送
                if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_REGISTER.getValue())) {
                    String param = "{\"code\":\"" + smsMessage.getCode() + "\",\"product\":\"赚翻啦\"}";
                    SmsServiceDayu.send("赚翻啦", captchaRequest.getMobile(), SmsTemplate.CAPTCHA_RE, param);
                    //修改密码
                } else if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_PASSWORD_CHANGE.getValue())) {
                    String param = "{\"code\":\"" + smsMessage.getCode() + "\",\"product\":\"赚翻啦\"}";
                    SmsServiceDayu.send("赚翻啦", captchaRequest.getMobile(), SmsTemplate.CAPTCHA_MODIFY_PASSWORD, param);
                    //忘记密码
                } else if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_PASSWORD_FORGET.getValue())) {
                    String param = "{\"code\":\"" + smsMessage.getCode() + "\",\"product\":\"赚翻啦\"}";
                    SmsServiceDayu.send("赚翻啦", captchaRequest.getMobile(), SmsTemplate.CAPTCHA_MODIFY_PASSWORD, param);
                    //支付宝绑定
                }else if (captchaRequest.getType().toString().equals(SMSType.CUSTOMER_BIND_ALIPAY.getValue())){
                    String param = "{\"code\":\"" + smsMessage.getCode() + "\",\"product\":\"赚翻啦\"}";
                    SmsServiceDayu.send("赚翻啦", captchaRequest.getMobile(), SmsTemplate.CAPTCHA_MODIFY_INFO, param);
                    //手机号绑定
                }else if (captchaRequest.getType().toString().equals(SMSType.TELEPHONE_BIND.getValue())){
                    String param = "{\"code\":\"" + smsMessage.getCode() + "\",\"product\":\"赚翻啦\"}";
                    SmsServiceDayu.send("赚翻啦", captchaRequest.getMobile(), SmsTemplate.CAPTCHA_MODIFY_INFO, param);
                }
            }
        } catch (Exception e) {
            logger.error(" 发送短信失败！", e);
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.UNKNOWN_ERROR);
        }
        captchaResponse.setSuccessful(ResultMessage.TRUE);
        captchaResponse.setMessage(StatusCode.SUCCESS.getMessage());
        captchaResponse.setCode(StatusCode.SUCCESS.getCode());

        return (T) captchaResponse;
    }

    private SMSMessage createMessage(CaptchaRequest captchaRequest, String debug) {
        SMSMessage smsMessage = new SMSMessage();
        smsMessage.setCreateAt(new Date());
        smsMessage.setPhone(captchaRequest.getMobile());
        String code = GenerationSmsCode.createRandom(Boolean.parseBoolean(debug));
        String text = String.format(Constants.SMS_TEXT, code);
        smsMessage.setType(captchaRequest.getType().toString());
        if (captchaRequest.getLimit_time() != null)
            smsMessage.setValidateTimeoutSeconds(captchaRequest.getLimit_time());
        smsMessage.setCode(code);
        smsMessage.setContent(text);
        //保存到缓存
        smsService.save(smsMessage.getPhone(), smsMessage, smsMessage.getValidateTimeoutSeconds() / 60);
        logger.debug("-----验证码----：{}", code);
        return smsMessage;
    }
}